package cn.com.codes.testCasePackageManage.blh;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import cn.com.codes.common.SecurityContextHolderHelp;
import cn.com.codes.common.dto.PageModel;
import cn.com.codes.common.util.StringUtils;
import cn.com.codes.framework.app.blh.BusinessBlh;
import cn.com.codes.framework.app.view.View;
import cn.com.codes.framework.common.JsonUtil;
import cn.com.codes.framework.common.ListObject;
import cn.com.codes.framework.exception.BaseException;
import cn.com.codes.framework.security.Visit;
import cn.com.codes.framework.security.VisitUser;
import cn.com.codes.framework.security.filter.SecurityContext;
import cn.com.codes.framework.security.filter.SecurityContextHolder;
import cn.com.codes.framework.transmission.events.BusiRequestEvent;
import cn.com.codes.iteration.blh.IterationBlh;
import cn.com.codes.object.TestCaseInfo;
import cn.com.codes.object.TestCasePackage;
import cn.com.codes.object.TestcasepkgOperationHistory;
import cn.com.codes.object.TypeDefine;
import cn.com.codes.object.User;
import cn.com.codes.object.UserTestCasePkg;
import cn.com.codes.overview.dto.DataVo;
import cn.com.codes.testCasePackageManage.dto.PkgCaseInfo;
import cn.com.codes.testCasePackageManage.dto.PkgTestCaseReal;
import cn.com.codes.testCasePackageManage.dto.TestCasePackageDto;
import cn.com.codes.testCasePackageManage.service.TestCasePackageService;


public class TestCasePackageBlh extends BusinessBlh {
	
	private static Logger log = Logger.getLogger(TestCasePackageBlh.class);
	private TestCasePackageService testCasePackageService;
	private IterationBlh iterationBlh;
	
	/**
	 * @return the testCasePackageService
	 */
	public TestCasePackageService getTestCasePackageService() {
		return testCasePackageService;
	}

	/**
	 * @param testCasePackageService the testCasePackageService to set
	 */
	public void setTestCasePackageService(
			TestCasePackageService testCasePackageService) {
		this.testCasePackageService = testCasePackageService;
	}
	
	public View goTestCasePkgMain(BusiRequestEvent req) throws BaseException{
		return super.getView();
	}
	
	public View viewHistoryRecord(BusiRequestEvent req) throws BaseException{
		return super.getView();
	}
	

	
	public View loadTestCasePackageList(BusiRequestEvent req) throws BaseException {
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		this.buildTestCasesPackageHql(testCasePackageDto);//拼接Hql
		PageModel pageModel = new PageModel();
		pageModel.setQueryHql(testCasePackageDto.getHql());
		pageModel.setHqlParamMap(testCasePackageDto.getHqlParamMaps());
		pageModel.setPageNo(testCasePackageDto.getPageNo());
		pageModel.setPageSize(testCasePackageDto.getPageSize());
		testCasePackageService.getJdbcTemplateWrapper().fillPageModelData(pageModel, TestCasePackage.class, null);
		this.setRealUser((List<TestCasePackage>)pageModel.getRows());
		String taskId = null;
		if(null != testCasePackageDto.getTestCasePackage()){
			taskId = testCasePackageDto.getTestCasePackage().getTaskId();
		}
		this.setRealVersion((List<TestCasePackage>)pageModel.getRows(), taskId);
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}
	
	public View loadTestCasePkgIds(BusiRequestEvent req){
		TestCasePackageDto dto = super.getDto(TestCasePackageDto.class, req);
		StringBuffer hql = new StringBuffer();
		hql.append("select new cn.com.codes.framework.common.ListObject(");
		hql.append(" packageId as keyObj ,packageName as valueObj ) from TestCasePackage ")
		.append(" where taskId=? ");
		String taskId = dto.getTestCasePackage().getTaskId();
		if(taskId==null||taskId==""){
			taskId = SecurityContextHolderHelp.getCurrTaksId();
		}
		List<ListObject> listDates  = testCasePackageService.findByHql(hql.toString(), taskId);
		super.writeResult(JsonUtil.toJson(listDates));
		
		return super.globalAjax();
	}
	
	
	private void setRealVersion(List<TestCasePackage> list,String taskId ){
		if(list==null||list.isEmpty()) {
			return ;
		}
		StringBuffer hql = new StringBuffer();
		hql.append("select new cn.com.codes.framework.common.ListObject(");
		hql.append(" versionId as keyObj ,versionNum as valueObj ) from SoftwareVersion ")
		.append(" where taskid=? order by seq desc ");
		//String taskId = dto.getTaskId();
		if(taskId==null||taskId==""){
			taskId = SecurityContextHolderHelp.getCurrTaksId();
		}
		List<ListObject> listDates  = testCasePackageService.findByHql(hql.toString(), taskId);
		if(listDates!=null&&!listDates.isEmpty()) {
			for(ListObject currVersion :listDates) {
				for(TestCasePackage tpg :list) {
					if(tpg.getExecVersionName()==null&&currVersion.getKeyObj().equals(tpg.getExecVersion())) {
						tpg.setExecVersionName(currVersion.getValueObj());
					}
				}
			}
			
		}
		
		
	}
	private void setRealUser(List<TestCasePackage> tpkgList) {
		if(tpkgList==null||tpkgList.isEmpty()) {
			return;
		}
		String hql  = " from UserTestCasePkg t where t.packageId in(:ids) ";
		List<String> tpgkIds = new ArrayList<String>();
		if(tpkgList != null &&!tpkgList.isEmpty()) {
			for(TestCasePackage tpkg :tpkgList) {
				tpgkIds.add(tpkg.getPackageId());
			}
		}
		Map praValuesMap = new HashMap(1);
		praValuesMap.put("ids", tpgkIds);
		List<UserTestCasePkg> upkgList = testCasePackageService.findByHqlWithValuesMap(hql, praValuesMap, false);
		if(upkgList!=null&&!upkgList.isEmpty()) {
			Iterator<UserTestCasePkg> it = upkgList.iterator();
			while(it.hasNext()){
				UserTestCasePkg upkg = it.next();
				for(TestCasePackage pkg :tpkgList) {
					if(upkg.getPackageId().equals(pkg.getPackageId())) {
						if(pkg.getUserTestCasePkgs()==null) {
							Set<UserTestCasePkg> set = new HashSet<UserTestCasePkg>();
							pkg.setUserTestCasePkgs(set);
						}
						pkg.getUserTestCasePkgs().add(upkg);
						it.remove();
					}
				}
			}
			
		}
		

	}
	
	public View isMyTpgk(BusiRequestEvent req) throws BaseException {
		
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		Map<String,Object> praValuesMap = new HashMap<String,Object>(3);
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT  tcp.id as package_id FROM t_testcasepackage tcp " + 
				"	JOIN t_user_testcasepkg tup ON tcp.id = tup.packageId " + 
				"	where   ");
		sql.append("     tup.userid = :userid and  tcp.taskId = :taskId and tcp.id = :tpkgId");
		praValuesMap.put("userid",  SecurityContextHolderHelp.getUserId());
		praValuesMap.put("taskId",   testCasePackageDto.getTaskId());
		praValuesMap.put("tpkgId",  testCasePackageDto.getPackageId());
		int count = testCasePackageService.getJdbcTemplateWrapper().getResultCountWithValuesMap(sql.toString(), "", praValuesMap);
		if(count>=1) {
			super.writeResult("exeCase");
		}else {
			super.writeResult("reviewCase");
		}
		
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          buildTestCasesPackageHql
	* 方法功能描述:    
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年9月12日 上午10:13:27
	*/
	private void buildTestCasesPackageHql(TestCasePackageDto testCasePackageDto) {
		StringBuilder hqlStr = new StringBuilder();
		
		Map<String,Object> hashMap = new HashMap<String,Object>();
		
		String userId = testCasePackageDto.getSelectedUserIds();
		if(userId!=null&&!"all".equals(userId)) {
			hqlStr.append(" SELECT  tcp.*,tcp.id as package_id,tcp.taskId as task_id FROM t_testcasepackage tcp " + 
					"	JOIN t_user_testcasepkg tup ON tcp.id = tup.packageId " + 
					"	where 1=1  ");
			hqlStr.append("  and   tup.userid = :userid");
			hashMap.put("userid",  userId);
		}else {
			hqlStr.append(" SELECT   tcp.*,tcp.id as package_id,tcp.taskId as task_id  FROM t_testcasepackage tcp "  + 
					"	where 1=1  ");
		}
		
		if(null != testCasePackageDto.getTestCasePackage()){
				hqlStr.append(" and tcp.taskId = :taskId");
				hashMap.put("taskId",  testCasePackageDto.getTestCasePackage().getTaskId());
		}
		
	    if(null != testCasePackageDto.getQueryParam()){
    	  hqlStr.append(" and tcp.package_name like :packageName");
    	  hashMap.put("packageName",  "%" + testCasePackageDto.getQueryParam() +"%");
        }
	    
	    if(!StringUtils.isNullOrEmpty(testCasePackageDto.getPackageIdJoin())){
	    	String iterMiddleTableInfoString = "";
			List<String> packageIdJs = new ArrayList<String>();
			String caseSql = "SELECT itp.package_id AS packageId "
					+ " FROM t_iteration_list itl RIGHT JOIN t_iteration_testcasepackage_real itp "
					+ " ON itl.iteration_id = itp.iteration_id "
					+ " WHERE itl.task_id = '"+testCasePackageDto.getTestCasePackage().getTaskId()+"' ";
			List<Map<String, Object>> maps = testCasePackageService.findBySqlByJDBC(caseSql.toString());
			if(null!=maps&&maps.size()>0){
				for (int i = 0; i < maps.size(); i++) {
					String packageId = (String) maps.get(i).get("packageId");
					iterMiddleTableInfoString = packageId+" "+iterMiddleTableInfoString;
				}
				
				String[] packageId = iterMiddleTableInfoString.split(" ");
				for(int i=0;i<packageId.length;i++){
					packageIdJs.add(packageId[i]);
				}
			}
			
			hqlStr.append(" and tcp.id not in (:packageIds) ");
			hashMap.put("packageIds", packageIdJs);
		}
	    
		hqlStr.append(" order by  tcp.update_time desc ");
	    testCasePackageDto.setHql(hqlStr.toString());
		if(log.isInfoEnabled()){
			log.info(hqlStr.toString());
		}
	
		testCasePackageDto.setHqlParamMaps(hashMap);
	}
	/** 
	* 方法名:          buildTestCasesPackageHql
	* 方法功能描述:    
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2018年9月12日 上午10:13:27
	*/


	public View selTestCase(BusiRequestEvent req) throws BaseException{
		return super.getView();
	}
	
	public View viewTestCase(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto dto = (TestCasePackageDto) req.getDto();
		String taskId = dto.getTaskId();
		if(taskId!=null&&!"".equals(taskId)){//从看板中过来时，不为空，要设置下，要不查看用例要报错
			SecurityContextHolderHelp.setCurrTaksId(taskId);
		}
		return super.getView();
	}
	
	public View executeTestCase(BusiRequestEvent req) throws BaseException{
		return super.getView();
	}
	
	public View viewTestCaseResult(BusiRequestEvent req) throws BaseException{
		return super.getView();
	}
	
	public View addOrEditCasePkg(BusiRequestEvent req) throws BaseException{
		return super.getView();
	}
	
	public View buildIterationAboutTestCase(BusiRequestEvent req) throws BaseException{
		return super.getView();
	}
	
	public View saveTestCasePackage(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		Date nowDate = new Date();
		testCasePackageDto.getTestCasePackage().setCreateTime(nowDate);
		testCasePackageDto.getTestCasePackage().setUpdateTime(nowDate);
		SecurityContext sc = SecurityContextHolder.getContext();
		Visit visit = sc.getVisit();
		VisitUser user =  null;
		if(visit!=null){
			user = visit.getUserInfo(VisitUser.class);
			testCasePackageDto.getTestCasePackage().setCreaterId(user.getId());
		}
		
		String taskId = testCasePackageDto.getTestCasePackage().getTaskId();
		if(taskId==null){
			taskId = SecurityContextHolderHelp.getCurrTaksId();
			 testCasePackageDto.getTestCasePackage().setTaskId(taskId);
		}
		boolean chkRest = testCasePackageService.reNameChkInTask("TestCasePackage", testCasePackageDto.getTestCasePackage().getPackageName(), "packageName",null,null, testCasePackageDto.getTestCasePackage().getTaskId());
		if(chkRest){
			super.writeResult("reName");
			return super.globalAjax();
		}                     
		testCasePackageService.saveTestCasePackage(testCasePackageDto); 
		
		super.writeResult("success");
		return super.globalAjax();
	}
	
	public View updateTestCasePackage(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		Date nowDate = new Date();
		testCasePackageDto.getTestCasePackage().setUpdateTime(nowDate);;
		String taskId = testCasePackageDto.getTestCasePackage().getTaskId();
		if(taskId==null){
			taskId = SecurityContextHolderHelp.getCurrTaksId();
			 testCasePackageDto.getTestCasePackage().setTaskId(taskId);
		}
		boolean chkRest = testCasePackageService.reNameChkInTask("TestCasePackage",  testCasePackageDto.getTestCasePackage().getPackageName(), "packageName", "packageId", testCasePackageDto.getTestCasePackage().getPackageId(),testCasePackageDto.getTestCasePackage().getTaskId());
		if(chkRest){
			super.writeResult("reName");
			return super.globalAjax();
		}
		
		//更新成功前先判断是否修改预期时间。若修改，则添加修改时间历史记录	
		List<TestCasePackage> testcasepkgList=testCasePackageService.findByProperties(TestCasePackage.class, new String[]{ "id"},new Object[]{testCasePackageDto.getTestCasePackage().getPackageId()});
		
		String userId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
		String userName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getName();
		TestcasepkgOperationHistory testcasepkgHistory = new TestcasepkgOperationHistory();

		if(testcasepkgList.size()>0){
			TestCasePackage testCasePackage = testcasepkgList.get(0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			
			String oldExpStartTime = testCasePackage.getExpectedStartTime()==null?"":sdf.format(testCasePackage.getExpectedStartTime());
			String oldExpEndTime = testCasePackage.getExpectedEndTime()==null?"":sdf.format(testCasePackage.getExpectedEndTime());
			String oldActualStartTime = testCasePackage.getActualStartTime()==null?"":sdf.format(testCasePackage.getActualStartTime());
			
			String newExpStartTime = sdf.format(testCasePackageDto.getTestCasePackage().getExpectedStartTime());
			String newExpEndTime = sdf.format(testCasePackageDto.getTestCasePackage().getExpectedEndTime());			
			String newActualStartTime =testCasePackageDto.getTestCasePackage().getActualStartTime()==null?"":sdf.format(testCasePackageDto.getTestCasePackage().getActualStartTime());

			//当原始时间与传入时间不一致时，添加一条历史记录
			String remarkStr = new String(); 
			
			if(!oldExpStartTime.equals(newExpStartTime)){
				remarkStr ="预计开始时间：" + oldExpStartTime + "->" + newExpStartTime;
			}
			
			if(!oldExpEndTime.equals(newExpEndTime)){
				remarkStr +="预计结束时间：" + oldExpEndTime + "->" + newExpEndTime;		
			}
			
            if(!StringUtils.isNullOrEmpty(oldActualStartTime.toString())){
            	if(!oldActualStartTime.equals(newActualStartTime)){
    				remarkStr +="实际开始时间：" + oldActualStartTime + "->" + newActualStartTime;		
    			}	
			}else{
				remarkStr +="实际开始时间：" + oldActualStartTime + "->" + newActualStartTime;	
			}
				
			
			testcasepkgHistory.setPackageId(testCasePackageDto.getTestCasePackage().getPackageId());
			testcasepkgHistory.setTaskId(taskId);
			testcasepkgHistory.setOperationPersonId(userId);
			testcasepkgHistory.setOperationPersonName(userName);
			testcasepkgHistory.setOperationTime(new Date());
			testcasepkgHistory.setOperationType("2");  //0：删除用例 ； 1：增加用例；  2：修改预计时间、 实际时间；
			testcasepkgHistory.setOperationDesc(remarkStr);
			
			//把之前的执行率
			testCasePackageDto.getTestCasePackage().setExeCount(testCasePackage.getExeCount());
			testCasePackageDto.getTestCasePackage().setNotExeCount(testCasePackage.getNotExeCount());

		}
      
		
		testCasePackageService.updateTestCasePackage(testCasePackageDto); 
		testCasePackageService.add(testcasepkgHistory);
		

		super.writeResult("success");
		return super.globalAjax();
	}
	
	public View deleteTestCasePkgById(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		  if(null != testCasePackageDto.getTestCasePackage()){
	    	   if(null != testCasePackageDto.getTestCasePackage().getPackageId()){
	    		   testCasePackageService.deleteTestCasePkgById(testCasePackageDto.getTestCasePackage().getPackageId()); 
	    	   }
		  }
		super.writeResult("success");
		return super.globalAjax();
	}
	
	
	public View getUserIdsByPackageId(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		String[] userIds = testCasePackageService.getUserIdsByPackageId(testCasePackageDto); 
		super.writeResult(JsonUtil.toJson(userIds));
		return super.globalAjax();
	}
	//查询某个用例包已分配的所有用例
	public View getSelTestCasesByPkgId(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		List<PkgTestCaseReal> lists = testCasePackageService.getSelTestCasesByPkgId(testCasePackageDto); 
		super.writeResult(JsonUtil.toJson(lists));
		return super.globalAjax();
	}
	//查询某个用例包已分配用例--分页
	public View getPaginationForSelTestCasesByPkgId(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		List<PkgCaseInfo> lists = testCasePackageService.getPaginationForSelTestCasesByPkgId(testCasePackageDto); 
		if(lists.size()!=0){
			this.setRelaUser(lists);
			this.setRelaTaskName(lists);
			this.setRelaType(lists);
		}
		PageModel pg = new PageModel();
		pg.setRows(lists);
		if(null != testCasePackageDto.getTestCasePackage()){
			if(null != testCasePackageDto.getTestCasePackage().getPackageId()){
				TestCasePackage testPkg = testCasePackageService.get(TestCasePackage.class, testCasePackageDto.getTestCasePackage().getPackageId());
				if(testPkg!=null&&testPkg.getExecVersion()!=null) {
					pg.setCountProName(testPkg.getExecVersion());
				}
			}
		}
		pg.setTotal(testCasePackageDto.getTotal());
		super.writeResult(JsonUtil.toJson(pg));
		return super.globalAjax();
	}
	
	private void setRelaType(List<PkgCaseInfo> lists){
		 Map<String,TypeDefine> typeMap= testCasePackageService.getRelaTypeDefine(lists, "priId","caseTypeId");
		 if(typeMap.isEmpty()){
			 return;
		 }
		 for(PkgCaseInfo obj:lists ){
			 if(typeMap.get(obj.getCaseTypeId().toString())!=null){
				 obj.setTypeName(typeMap.get(obj.getCaseTypeId().toString()).getTypeName());
			 }
			 if(typeMap.get(obj.getPriId().toString())!=null){
				 obj.setPriName(typeMap.get(obj.getPriId().toString()).getTypeName());
			 }
		 }
		 typeMap = null;
	}
	private void setRelaUser(List<PkgCaseInfo> lists){
		Map<String,User> userMap= testCasePackageService.getRelaUserWithName(lists, "createrId","auditId");
		User own = null;
		for(PkgCaseInfo obj :lists){
			own = userMap.get(obj.getCreaterId());
			if(own!=null)
				obj.setAuthorName(own.getUniqueName());
			if(obj.getAuditId()!=null){
				own = userMap.get(obj.getAuditId());
				if(own==null){
					continue;
				}
				obj.setAuditerNmae(own.getUniqueName());					
			}
			own = null;
		}
		own= null;
		userMap = null;
	}
	
	private void setRelaTaskName(List<PkgCaseInfo> lists){
		if(lists==null||lists.isEmpty()){
			return;
		}
		Map<String,ListObject> taskMap= testCasePackageService.getRelaTestTasks(lists, "taskId");
		ListObject lstObj = null;
		for(PkgCaseInfo obj :lists){
			lstObj = taskMap.get(obj.getTaskId());
			if(lstObj==null){
				continue;
			}
			obj.setTaskName(lstObj.getValueObj());
		}
		lstObj= null;
		taskMap = null;
	}
	
	public View saveTestCase_CasePkg(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		testCasePackageService.saveTestCase_CasePkg(testCasePackageDto); 
		super.writeResult("success");
		return super.globalAjax();
	}
	
	public View getBugStaticsByPkgId(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		if(testCasePackageDto !=null && testCasePackageDto.getTestCasePackage() !=null && !StringUtils.isNullOrEmpty(testCasePackageDto.getTestCasePackage().getPackageId())){
			DataVo dataVo = testCasePackageService.getBugStaticsByPkgId(testCasePackageDto); 
			super.writeResult(JsonUtil.toJson(dataVo));
		}else{
			super.writeResult("操作失败，请稍后再试");
		}
	
		return super.globalAjax();
	}
	
	public View delTestCase_CasePkgByPkgCaseId(BusiRequestEvent req) throws BaseException{
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		if(testCasePackageDto !=null && !StringUtils.isNullOrEmpty(testCasePackageDto.getPkgCaseId())){
	    	testCasePackageService.delTestCase_CasePkgByPkgCaseId(testCasePackageDto.getPkgCaseId(),testCasePackageDto.getTestCaseId().toString(),testCasePackageDto.getPackageId()); 
	    	super.writeResult("success");
		}else{
			super.writeResult("操作失败，请稍后再试");
		}
		return super.globalAjax();
	}
	
	
	/** 
	* 方法名:          testcasePkgHisRecordList
	* 方法功能描述:      操作历史记录
	* @param:         
	* @return:        
	* @Author:        
	* @Create Date:   2019年3月20日 下午5:14:03
	*/
	public View testcasePkgHisRecordList(BusiRequestEvent req){
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		Map praValues = new HashMap();
	
		//拼接sql
		StringBuilder hqlStr = new StringBuilder();
		//查询 包操作历史
		if(!StringUtils.isNullOrEmpty(testCasePackageDto.getQueryParam()) && testCasePackageDto.getQueryParam().equals("package")){
			hqlStr.append("select toh.id as id,toh.task_id as taskId,toh.package_id as packageId,toh.operation_person_name as operationPersonName,toh.operation_time as operationTime,toh.operation_desc as operationDesc,toh.operation_type as operationType,tcp.package_name as packageName ");
			hqlStr.append(" from t_testcasepkg_operation_history toh,t_testcasepackage tcp ");
			hqlStr.append(" where toh.package_id =:packageId");
			hqlStr.append(" and tcp.id=toh.package_id ");
			hqlStr.append(" and toh.testcase_id is null");
			hqlStr.append(" order by toh.operation_time desc");
			
			praValues.put("packageId", testCasePackageDto.getTestCasePackage().getPackageId());
		}else{
			//操作用例操作历史
			hqlStr.append(" select toh.id as id,toh.task_id as taskId,stt.PRO_NAME as proName,toh.package_id as packageId,toh.testcase_id as testCaseId,toh.operation_person_id as operationPersonId,toh.operation_type as operationType,toh.operation_time as operationTime,");
			hqlStr.append(" tci.TESTCASEDES as testcaseDesc,toh.operation_person_name as operationPersonName,toh.operation_history as operationHistory from t_testcasepkg_operation_history toh ,t_single_test_task stt,T_TESTCASEBASEINFO tci where toh.task_id=stt.TASKID and tci.TESTCASEID=toh.testcase_id and toh.package_id=:packageId order by toh.operation_time desc");
			
			praValues.put("packageId", testCasePackageDto.getTestCasePackage().getPackageId());
		}
	
		PageModel pageModel = new PageModel();
		pageModel.setQueryHql(hqlStr.toString());
		pageModel.setHqlParamMap(praValues);
		pageModel.setPageNo(testCasePackageDto.getPageNo());
		pageModel.setPageSize(testCasePackageDto.getPageSize());
		testCasePackageService.getJdbcTemplateWrapper().fillPageModelData(pageModel,null, "id");
		testCasePackageService.getJdbcTemplateWrapper().converDbColumnName2ObjectPropName((List<Map<String, Object>>) pageModel.getRows());
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}
	
	/** 
	* 方法名:          HisRecordListForPkg
	* 方法功能描述:      操作历史记录--包操作
	* @param:         
	* @return:        
	* @Author:        
	* @Create Date:   2019年3月20日 下午5:14:03
	*/
	public View hisRecordListForPkg(BusiRequestEvent req){
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		Map praValues = new HashMap();
	
		//拼接sql
		StringBuilder hqlStr = new StringBuilder();
		hqlStr.append("select toh.id as id,toh.task_id as taskId,stt.PRO_NAME as proName,toh.package_id as packageId,toh.testcase_id as testCaseId,toh.operation_person_id as operationPersonId,toh.operation_type as operationType,toh.operation_time as operationTime,");
		hqlStr.append("tci.TESTCASEDES as testcaseDesc,toh.operation_person_name as operationPersonName,toh.operation_history as operationHistory from t_testcasepkg_operation_history toh ,t_single_test_task stt,T_TESTCASEBASEINFO tci where toh.task_id=stt.TASKID and tci.TESTCASEID=toh.testcase_id and toh.package_id=:packageId order by toh.operation_time desc");
		praValues.put("packageId", testCasePackageDto.getTestCasePackage().getPackageId());
		PageModel pageModel = new PageModel();
		pageModel.setQueryHql(hqlStr.toString());
		pageModel.setHqlParamMap(praValues);
		pageModel.setPageNo(testCasePackageDto.getPageNo());
		pageModel.setPageSize(testCasePackageDto.getPageSize());
		testCasePackageService.getJdbcTemplateWrapper().fillPageModelData(pageModel,null, "id");
		testCasePackageService.getJdbcTemplateWrapper().converDbColumnName2ObjectPropName((List<Map<String, Object>>) pageModel.getRows());
		super.writeResult(JsonUtil.toJson(pageModel));
		return super.globalAjax();
	}
	
	public View findCaseIdByModuleIds(BusiRequestEvent req){
		TestCasePackageDto testCasePackageDto = (TestCasePackageDto) req.getDto();
		String taskId = SecurityContextHolderHelp.getCurrTaksId();
		String moduleIds= testCasePackageDto.getOtherCaseModuleIds();
		String[] moduleList = moduleIds.split(",");
		
        String sql ="SELECT DISTINCT oli.MODULEID as moduleId, oli.MODULENum as moduleNum FROM t_outlineinfo oli WHERE 1=1 AND oli.taskId='" + taskId + "' AND oli.MODULEID in (";
        for(int i=0;i<moduleList.length;i++){
        	sql +="'" + moduleList[i] + "'";
        	if(i<moduleList.length-1){
        		sql +=",";
        	}
        }
        sql += ")";
        List<Object[]> countlist = testCasePackageService.findBySql(sql, null, null);
        List<String> moduleNumList = new ArrayList<String>();
        if(countlist.size()>0){
          for(int i=0;i<countlist.size();i++) {
        	  moduleNumList.add(countlist.get(i)[1].toString());
          }
        }
        
        List<TestCaseInfo> testCaseInfos= testCasePackageService.findCaseIdByModuleIds(moduleNumList,taskId,testCasePackageDto.getTagName(),testCasePackageDto.getStatus());	
        testCasePackageDto.setOtherCaseIdNum(testCaseInfos.size());
        testCasePackageDto.setOtherCaseModuleNum(moduleNumList);
		super.writeResult(JsonUtil.toJson(testCasePackageDto));
		return super.globalAjax();
	}
	
	private  Long[] StringArrayToLongArray(String[] stringArray)
    {
        List<Long> list=new ArrayList<>();
        for (String str: stringArray) {
            try {
                list.add(Long.parseLong(str));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        Long[] longArray=list.toArray(new Long[list.size()]);
        return longArray;
    }

	public IterationBlh getIterationBlh() {
		return iterationBlh;
	}

	public void setIterationBlh(IterationBlh iterationBlh) {
		this.iterationBlh = iterationBlh;
	}


	
}
